<?php
/**
 * Created By PhpStorm
 * Author: patrick wu
 * Date: 2020/12/31
 * Time: 16:45
 */
namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Service\Admin\SystemService;
use App\Constant\ErrorConstant;

class SystemController extends BaseController
{
    protected $service;

    public function __construct(Request $request, SystemService $service)
    {
        parent::__construct($request);

        $this->service  =   $service;
    }

    /**
     * 盒子后台登录
     * @return \Illuminate\Http\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function loginSystem()
    {
        $validator  =   Validator::make($this->request->post(), [
            'account'   =>  'required|string|max:50',
            'password'  =>  'required|string|max:50',
            'source'    =>  'required|in:1,2'
        ], [
            'account.required'  =>  '登录账号不能为空',
            'account.string'    =>  '登录账号必须为字符',
            'account.max'       =>  '登录账号过长',

            'password.required' =>  '登录密码不能为空',
            'password.string'   =>  '登录密码必须为字符',
            'password.max'      =>  '登录密码过长',

            'source.required'   =>  '登录来源不能为空',
            'source.in'         =>  '登录来源错误'
        ]);

        if ($validator->fails()) {
            return $this->errorResponse(ErrorConstant::ADMIN_SYSTEM_LOGIN_ERROR, $validator->errors()->first());
        }

        $account    =   $this->request->post('account');
        $password   =   $this->request->post('password');
        if ($this->request->post('source') == 1) {
            [$flag, $result]    =   $this->service->ownerLogin($account, $password);
        } else {
            [$flag, $result]    =   $this->service->systemLogin($account, $password);
        }

        if ($flag) {
            return $this->successResponse($result);
        } else {
            return $this->errorResponse(ErrorConstant::ADMIN_SYSTEM_LOGIN_ERROR, $result);
        }
    }
}
